import axios from 'axios';
import {COOKIE_KEY} from '../../src/utils/constant';
import {setI18nResource} from '../../src/utils/i18nUtil';

const requireContext = (require as any).context('../../src/dataSources/i18n/resource', true, /\.ts$/);
const langList = requireContext.keys().map(filePath => filePath.split(/[\\./]/).slice(-2)[0]);

export async function reloadI18n() {
	const res = await axios.post('http://micro.tradechina.com/blade-web-design/jztSystemResourceData/selectAllLan', {});
	const lang_data_map = {};
	const keySet = new Set();
	res.data.data.forEach(item => {
		const {code, CODE = code, lang, LANG = lang, value, VALUE = value, isDeleted, IS_DELETED = isDeleted} = item;
		const data = (lang_data_map[LANG] = lang_data_map[LANG] || {});
		if (!IS_DELETED) {
			data[CODE] = VALUE;
			keySet.add(CODE);
		}
	});
	langList.forEach(lang => {
		const data = lang_data_map[lang];
		const allValue = Object.values(data);
		const effectValue = allValue.filter(Boolean);
		if (effectValue.length) {
			console.debug(`更新[${lang}], 数量: ${allValue.length}, 有效: ${effectValue.length}`);
		} else {
			console.warn(`更新[${lang}], 数量: ${allValue.length}, 有效: ${effectValue.length}`);
		}
		setI18nResource(lang, lang_data_map[lang]);
	});
}

export async function initI18n() {
	requireContext.keys().forEach(filePath => {
		// 获取组件配置
		const data = requireContext(filePath);
		const [lang] = filePath.split(/[\\./]/).slice(-2);
		setI18nResource(lang, data.default);
	});
}

export function setResLanguage(res, lang, domain) {
	res.cookie(COOKIE_KEY.LANGUAGE, lang, {domain, path: '/', expires: new Date(Date.now() + 10 * 365.256 * 24 * 3600 * 1000)});
}
